<?php
declare (strict_types=1);

namespace app\controller;

use app\model\ActivityGoods;
use app\model\ApplySamples;
use app\model\DarenSwBind;
use app\model\DyUser;
use app\model\ExpressCompany;
use app\model\TrackRecord;
use app\model\UserInfo;
use app\model\UserRole;
use app\model\Wiseman;
use app\traits\CommonTrait;
use app\traits\TemplateMsgTrait;
use app\validate\OwnSendSample;
use app\validate\PhoneCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\model\User;

class SwDaren
{
    use CommonTrait;
    use TemplateMsgTrait;

    //达人广场 -- 跟进列表 -- 合作列表
    public function index()
    {
        $uid = getUid();
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        //0达人广场 1 跟进列表 2合作列表
        $follow = Request::get('follow', 0);
        $dyName = Request::get('dy_name', '');
        $where = [];
        $where[] = ['author_id', '<>', ''];
        if ($dyName != '') {
            $where[] = ['nickname', 'like', "%" . $dyName . '%'];
        }
        switch ($follow) {
            default:
            case 0:
                $where[] = ['user_id', '=', 0];
                $where[] = ['is_worked', '=', 0];
                $order = 'create_time';
                break;
            case 1:
                $where[] = ['user_id', '=', $uid];
                $where[] = ['is_worked', '=', 0];
                $order = 'track_time';
                break;
            case 2:
                $where[] = ['user_id', '=', $uid];
                $where[] = ['is_worked', '=', 1];
                $order = 'co_work_time';
                break;
        }
        $list = Wiseman::where($where)->field('id,dy_id,nickname as dy_name,avatar,goods_main_cate as dh_cate_tag,product_num,volume')
            ->order($order, 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $list);
    }

    //达人信息
    public function drInfo()
    {
        $dyUserId = Request::get('dy_user_id');
        if (!$dyUserId) {
            return $this->apiJson(-1, '缺少dy_user_id参数');
        }
        $wiseMan = Wiseman::where(['id' => $dyUserId])
            ->field('id,user_id,avatar,nickname as dy_name,city,goods_main_cate as dh_cate_tag,dy_id,phone,introduction as dy_intro,
            fans_num,link_num,works_num,product_num,sale_num,author_id')
            ->findOrEmpty();
        if ($wiseMan->isEmpty()) {
            return $this->apiJson(-1, '达人不存在');
        }
        if ($wiseMan['user_id'] != 0) {
            $user = User::where(['id' => $wiseMan['user_id']])->field('name,wx_nickname')->find();
            $userName = $user['name'];
            $wxNickname = $user['wx_nickname'];
        } else {
            $userName = '';
            $wxNickname = '';
        }
        if($wiseMan['fans_num']>=10000){
            $wiseMan['fans_num'] = round($wiseMan['fans_num']/10000,2).'w';
        }
        if($wiseMan['link_num']>=10000){
            $wiseMan['link_num'] = round($wiseMan['link_num']/10000,2).'w';
        }
        $wiseMan['user_name'] = $userName;
        $wiseMan['wx_nickname'] = $wxNickname;
        return $this->apiJson(1, 'success', $wiseMan);
    }

    //达人跟进
    public function drTrack()
    {
        $uid = getUid();
        $dyUserId = Request::post('dy_user_id');
        $remark = Request::post('remark');
        if (!$dyUserId) {
            return $this->apiJson(-1, '缺少dy_user_id参数');
        }
        if (!$remark && $remark != '0') {
            return $this->apiJson(-1, '请输入备注');
        }
        if (mb_strlen($remark) > 255) {
            return $this->apiJson(-1, '备注不能超过255个字');
        }
        Wiseman::where(['id' => $dyUserId])->update(['user_id' => $uid,'track_time'=>time()]);
        TrackRecord::create([
            'sw_user_id' => $uid,
            'dy_user_id' => $dyUserId,
            'remark' => $remark
        ]);
        return $this->apiJson(1, 'success');
    }

    // 跟进记录
    public function trackRecord()
    {
        $uid = getUid();
        $dyUserId = Request::get('dy_user_id');
        if (!$dyUserId) {
            return $this->apiJson(-1, '缺少dy_user_id参数');
        }
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $records = TrackRecord::where(['sw_user_id' => $uid, 'dy_user_id' => $dyUserId])->field('id,remark,create_time')
            ->order('create_time', 'desc')
            ->paginate(['page' => $currentPage, 'list_rows' => $perPage]);
        return $this->apiJson(1, 'success', $records);
    }

    // 商务自行发样
    public function ownSendSample()
    {
        $uid = getUid();
        $dyUserId = Request::post('dy_user_id');
        $activityGoodsId = Request::post('activity_goods_id');
        if (!$activityGoodsId) {
            return $this->apiJson(-1, '缺少activity_goods_id参数');
        }
        $goodsIdArr = explode(',', $activityGoodsId);
        $count = ActivityGoods::whereIn('id', $activityGoodsId)->where(['status' => 1])->count();
        if ($count != count($goodsIdArr)) {
            return $this->apiJson(-1, '参数错误');
        }
        $name = Request::post('name');
        $contactPhone = Request::post('phone');
        $expressNo = Request::post('express_no');
        $expressCompanyId = Request::post('express_company_id');
        $addressData = [
            'dy_user_id' => $dyUserId,
            'name' => $name,
            'phone' => $contactPhone,
            'province' => Request::post('province'),
            'city' => Request::post('city'),
            'district' => Request::post('district'),
            'detail_address' => Request::post('detail_address'),
            'express_no' => $expressNo,
            'express_company_id' => Request::post('express_company_id')
        ];
        try {
            validate(OwnSendSample::class)->check($addressData);
        } catch (ValidateException $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $wiseMan = Wiseman::where(['id' => $dyUserId])->field('user_id,author_id,phone')->findOrEmpty();
        if ($wiseMan->isEmpty()) {
            return $this->apiJson(-1, '达人不存在');
        }
        //达人user
        $user = DyUser::where(['dy_uid' => $wiseMan['author_id']])->field('user_id')->findOrEmpty();
        if ($user->isEmpty()) {
            return $this->apiJson(-1, '达人不存在');
        }
        if (!$wiseMan['phone']) {
            return $this->apiJson(-1, '你未设置达人的手机号,暂不能发样');
        }
        //快递公司
        $expressCompany = ExpressCompany::where(['id' => $expressCompanyId])->find();
        $province = Db::name('china_districts')->where(['code' => Request::post('province')])->field('code,name')->find();
        $city = Db::name('china_districts')->where(['code' => Request::post('city')])->field('code,name')->find();
        $district = Db::name('china_districts')->where(['code' => Request::post('district')])->field('code,name')->find();
        $sample = [];
        $sampleNo = $this->generateSampleNo();

        foreach ($goodsIdArr as $k => $v) {
            $sample[$k] = [
                'user_id' => $user['user_id'],
                'sw_user_id' => $uid,
                'sample_no' => $sampleNo,
                'activity_goods_id' => $v,
                'dy_uid' => $wiseMan['author_id'],
                'contact_name' => $name,
                'contact_phone' => $contactPhone,
                'address' => $province['name'] . $city['name'] . $district['name'] . Request::post('detail_address'),
                'express_no' => $expressNo,
                'express_name' => $expressCompany['name'],
                'type' => 2,
                'status' => 1,
                'create_time' => date('Y-m-d H:i:s', time()),
                'update_time' => date('Y-m-d H:i:s', time())
            ];
        }
        Db::startTrans();
        try {
            Db::name('apply_samples')->insertAll($sample);
            Wiseman::where(['id' => $dyUserId])->update(['is_worked' => 1,'co_work_time'=>time()]);
            $openId = UserInfo::where(['user_id'=>$user['user_id']])->value('openid');
            //发送通知
            if($openId){
                $product = ActivityGoods::whereIn('id',$goodsIdArr)->field('product_name')->select();
                $productName = '';
                foreach ($product as $v){
                    $productName .= $v['product_name'].', ';
                }
                $productName = substr($productName,0,-2);
                $templateId = config('app.template.sample_notice');
                $pagePath = 'pakeageDaren/pages/select/index?title='.$sampleNo;
                $data = [
                    "first" => [
                        "value" => "嗖嗖嗖，领样商品已经发货啦"
                    ],
                    "keyword1" => [
                        "value" => $productName
                    ],
                    "keyword2" => [
                        "value" => $expressCompany['name']
                    ],
                    "keyword3" => [
                        "value" => $expressNo
                    ],
                    "keyword4" => [
                        "value" =>$name.' '.$contactPhone.' '.$province['name'] . $city['name'] . $district['name'] . Request::post('detail_address')
                    ],
                    "remark" => [
                        "value" => "点击查看领样详情"
                    ],
                ];
                $result = $this->uniformMessageSend($openId, $templateId, $data,$pagePath);
                if ($result['code'] != 1) {
                    Log::info($result);
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Log::info('自行发样失败:'.$e->getMessage());
            Db::rollback();
            return $this->apiJson(-1, '发样失败');
        }
        return $this->apiJson(1, 'success');
    }

    //修改手机号
    public function setWiseManPhone()
    {
        $uid = getUid();
        $dyUserId = Request::post('dy_user_id');
        $phone = Request::post('phone');
        try {
            validate(PhoneCheck::class)->check(['phone' => $phone, 'type' => 1]);
        } catch (ValidateException $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $wiseMan = Wiseman::where(['id' => $dyUserId])
            ->field('phone,dy_id,author_id,nickname,avatar,introduction,goods_main_cate,fans_num,gender,city,user_id')
            ->findOrEmpty();
        if ($wiseMan->isEmpty()) {
            return $this->apiJson(-1, '达人不存在');
        }
        //跟进过的达人才可以修改
        if ($wiseMan['user_id'] != $uid) {
            return $this->apiJson(-1, '你无权限修改');
        }
        $city = explode('·', $wiseMan['city']);
        Wiseman::where(['id' => $dyUserId])->update(['phone' => $phone]);
        $dyUser = DyUser::where(['dy_uid' => $wiseMan['author_id']])->findOrEmpty();
        if ($dyUser->isEmpty()) {
            //创建用户
            $userExist = User::where(['phone' => $phone])->findOrEmpty();
            if ($userExist->isEmpty()) {
                $userId = User::insertGetId(['phone' => $phone,'create_time'=>time(),'update_time'=>time()]);
                UserRole::create(['uid' => $userId, 'rid' => 4]);
            } else {
                $userId = 0;
            }
            $dyUserData = [
                'user_id' => $userId,
                'open_id' => '',
                'union_id' => '',
                'dy_id' => $wiseMan['dy_id'],
                'dy_uid' => $wiseMan['author_id'],
                'phone' => $phone,
                'dy_name' => $wiseMan['nickname'],
                'dy_intro' => $wiseMan['introduction'],
                'avatar' => $wiseMan['avatar'],
                'dh_cate_tag' => $wiseMan['goods_main_cate'],
                'fans' => $wiseMan['fans_num'],
                'gender' => $wiseMan['gender'],
                'country' => '其他',
                'province' => $city[0],
                'city' => $city[1],
                'is_auth' => 1
            ];
            DyUser::create($dyUserData);
        } else {
            DyUser::where(['dy_uid' => $wiseMan['dy_uid']])->update(['phone' => $phone]);
        }
        return $this->apiJson(1, 'success');
    }

    //达人商务绑定
    public function swDarenBind()
    {
        $uid = getUid();
        $swUserId = Request::post('sw_user_id', 0);
        if (!$swUserId) {
            return $this->apiJson(-1, '缺少参数');
        }
        if ($swUserId == $uid) {
            return $this->apiJson(1, 'success');
        }
        $swUserRole = UserRole::where(['uid' => $swUserId, 'rid' => 4])->findOrEmpty();
        Log::info($swUserRole);
        if (!$swUserRole->isEmpty()) {
            $bind = DarenSwBind::where(['dr_user_id' => $uid])->findOrEmpty();
            Log::info($bind);
            if ($bind->isEmpty()) {
                DarenSwBind::create(['sw_user_id' => $swUserId, 'dr_user_id' => $uid]);
            } else {
//            if($swUserId != $bind['sw_user_id']){
//               // return $this->apiJson(-1,'你已经绑定其他商务了');
//            }
            }
        }
        return $this->apiJson(1, 'success');
    }
}
